const express = require('express');
const Response = require('../utils/Response.js')
const pool = require('../utils/db.js')
const Joi = require('joi')
const AlipayFormData = require("alipay-sdk/lib/form").default;
const alipaySdk = require('../utils/alipay')

const router = express.Router();


/**
 * 提交支付
 */
router.post('/pay/submit', function (req, res) {
  let { tid, phoen, name, date, price } = req.body;
  let schema = Joi.object({
    tid: Joi.number().required(),
    phone: Joi.number().required(),
    name: Joi.string().required(),
    date: Joi.string().required(),
    price: Joi.number().required()
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    res.send(Response.error(400, error));
    return; // 结束
  }

  //获取详情
  // let detail = getrr(tid);
  //组装参数
  // let formData = assemblePayParams(price, "门票预订", "");

  toPay(tid, price, res);
});

async function getrr(tid) {
  let sql = "select * from ticket where tid = ?";
  let detail = await pool.querySync(sql, [tid])
  return detail;
}

async function toPay(tid, price, res) {
  let sql = "select * from ticket where tid = ?";
  let detail = await pool.querySync(sql, [tid])
  let formData = assemblePayParams(price, detail[0].title, detail[0].detail);
  //提交支付
  const result = await alipaySdk.exec("alipay.trade.page.pay", {}, { formData: formData });
  console.log(result);
  // 将结果封装，返回给客户端
  res.json({
    code: 200,
    msg: "OK",
    url: result
  });
}

function assemblePayParams(amount, itemName, itemDesc) {
  let orderNo = getOrderNo();
  const formData = new AlipayFormData();
  formData.setMethod('get');
  formData.addField('bizContent', {
    outTradeNo: orderNo, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
    productCode: 'FAST_INSTANT_TRADE_PAY', // 销售产品码，与支付宝签约的产品码名称,仅支持FAST_INSTANT_TRADE_PAY
    totalAmount: amount + '', // 订单总金额，单位为元，精确到小数点后两位
    subject: itemName, // 订单标题
    body: itemDesc, // 订单描述
  });
  // 表示异步通知回调,
  // formData.addField('notifyUrl', 'https://www.baidu.com');
  // 付款成功的跳转页面
  formData.addField('returnUrl', 'http://localhost:3010');
  return formData;
}

function getOrderNo() {
  const min = 100000;                            //最小值
  const max = 999999;                            //最大值
  const range = max - min;                         //取值范围差
  const random = Math.random();                     //小于1的随机数
  const result = min + Math.round(random * range);  //最小数加随机数*范围差
  orderNo = "CYJ" + new Date().getTime() + result;
  return orderNo;
}

/**
 * 查询支付结果
 */
router.get('/pay/query', function (req, res) {
  let { tid } = req.query;
  let schema = joi.object({
    tid: joi.required(), //tid必填
  });
  let { err, value } = schema.validate(req.query);
  if (err) {
    res.send(Response.error(400, err));
    return;
  }
  //根据ID查询
  let sql = "select * from ticket where tid = ?";
  pool.query(sql, [tid], (err, result) => {
    if (err) {
      res.send(Response.error(500, err));
      throw err;
    }
    // 将结果封装，返回给客户端
    res.send(Response.ok(result[0]));
  });
});

module.exports = router;